﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PPP.Utils {
    /// <summary>
    /// Helper Class to do something on data structures.
    /// 
    /// <list type="bullet">
    /// <item>
    /// <term>Author</term>
    /// <description>Sebastian Will</description>
    /// </item>
    /// </list>
    /// 
    /// </summary>  
    public static class DataUtils {

        /// <summary>
        /// Sort the element of a <see cref="ObservableCollection{TSource}"/>.
        /// </summary>
        /// <typeparam name="TSource">The typ of the element in the collection.</typeparam>
        /// <typeparam name="TKey">The typ of the sort creteria.</typeparam>
        /// <param name="source">The collection.</param>
        /// <param name="keySelector">A function which select the sorting key.</param>
        /// <param name="comparer">A <see cref="IComparer{TKey}"/> for a user-defined sorting.<para/>  
        /// IF <c>null</c> is passed, the default comparison is applied.</param>
        /// <param name="direction"></param>
        public static void Sort<TSource, TKey>(this ObservableCollection<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer, ListSortDirection direction) {
            TSource[] sortedList;

            switch (direction) {
                case System.ComponentModel.ListSortDirection.Ascending: {
                        if (comparer == null)
                            sortedList = source.OrderBy(keySelector).ToArray();
                        else
                            sortedList = source.OrderBy(keySelector, comparer).ToArray();
                        break;
                    }
                case System.ComponentModel.ListSortDirection.Descending: {
                        if (comparer == null)
                            sortedList = source.OrderByDescending(keySelector).ToArray();
                        else
                            sortedList = source.OrderByDescending(keySelector, comparer).ToArray();
                        break;
                    }
                default:
                    sortedList = source.ToArray();
                    break;
            }
            
            source.Clear();
            foreach (var item in sortedList)
                source.Add(item);
        }
    }
}


//switch (direction)
//     {
//        case System.ComponentModel.ListSortDirection.Ascending:
//           {
//              ApplySort(Items.OrderBy(keySelector));
//              break;
//           }
//        case System.ComponentModel.ListSortDirection.Descending:
//           {
//              ApplySort(Items.OrderByDescending(keySelector));
//              break;
//           }
//     }         